<template>
  <div
        style="width: 100%">
    <span class="tjsqstyle">
      <p class="shenqing">已添加物料
         <!-- 返回按钮 -->
      <el-button type="primary" icon="el-icon-back" size="mini" @click="goback">返回上一页</el-button>
      </p>
      <el-form :model="queryParams" ref="queryForm" :inline="true" style="margin-left: 15px" :rules="rules" >
        <el-form-item label="申请名称" >
          <el-input
            v-model="queryParams.pickName"
            placeholder="请输入申请名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="申请月份" prop="planMonth" >
          <el-date-picker
            v-model="queryParams.planMonth"
            type="month"
            format="yyyy-MM"
            value-format="yyyy-MM"
            size="small"
            placeholder="选择月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用途" >
          <el-input
            v-model="queryParams.useing"
            placeholder="请输入用途"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="仓库名称" prop="wnameSJ">
            <el-select :disabled="bukedianji" size="small" v-model="queryParams.wnameSJ" placeholder="请选择上级仓库" ref="selectReport">
              <el-option :value="queryParams.id" :label="queryParams.wname" style="width:199px;height:200px;overflow: auto;background-color:#fff">
                <el-tree
                  node-key="id"
                  :default-expanded-keys="[1]"
                  highlight-current
                  :data="reportData"
                  :props="defaultProps"
                  @node-click="handleNodeClickSJ"
                ></el-tree>
              </el-option>
            </el-select>
         </el-form-item>

      </el-form>

      <div style="margin-left: 15px;margin-bottom: 15px" >
        <el-button type="primary"  icon="el-icon-plus" size="mini" @click="choose">选择</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteBtn">删除</el-button>
        <el-button type="success"  :loading="loading"  icon="el-icon-plus" size="mini" @click="tijiao" style="width: 100px">保存</el-button>
        <el-upload
            style="display:inline-block;"
            accept=".xlsx, .xls"
            :show-file-list="false"
            :http-request="httpRequest"
            :action="baseUrl()+'/material/apply/statistics/importWz'"
        >
        <el-button v-hasPermi="['suppliesLLGL:zjRukume:toLeadSuccess']" size="mini" type="info" icon="el-icon-upload">导入</el-button>
        </el-upload>
      </div>

      <el-table  :data="queryParams.wzPickingApplyInfos" stripe style="margin-left: 15px;width: 1526px"
                 @selection-change="handleSelectionChange"
                 border>
        <el-table-column align="center" type="selection" width="80"></el-table-column>
        <el-table-column align="center" type="index" label="序号"  width="55"  />
        <el-table-column align="center" label="物料编码" property="mno" width="180" :show-overflow-tooltip="true"  ></el-table-column>
        <el-table-column align="center" label="物料名称"  property="mname" width="180" ></el-table-column>
        <el-table-column align="center" label="物料规格"  property="mmodel" width="180" ></el-table-column>
        <el-table-column align="center" label="单位"  property="unit" width="180" ></el-table-column>
        <el-table-column align="center" label="计划价" width="180" property="planPrice"  >
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.planPrice" placeholder="" @input="keydownBtn(scope.row)"></el-input>
        </template>
        </el-table-column>
        <el-table-column align="center" label="入库数量"  property="demandNum" width="130" >
          <template slot-scope="scope">
            <el-input type="number" v-model="scope.row.demandNum" placeholder=""
            :ref="'mark'+scope.$index"
            @keyup.enter.native='keyupBtn(scope)'
            @input="xqkeydownBtn(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="用途"  property="useing" width="180" >
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.useing" placeholder="" ></el-input>
        </template>
        </el-table-column>
        <el-table-column align="center" label="备注" property="note" width="180" >
          <template slot-scope="scope">
            <el-input type="text" v-model="scope.row.note" placeholder=""></el-input>
        </template>
        </el-table-column>

      </el-table>
    </span>
    <!-- <div style="margin-left: 15px;margin-bottom:300px;width: 90%;" class="inputme" >
      <input type="text" style='width:80px;background-color: #fff;' disabled="disabled">
      <input type="text" style='width:55px' disabled="disabled">
      <input type="text" style='width:180px;padding-left:10px' placeholder="请输入物料编码并回车" v-model="wlBianma" @keyup="cxwlMEssage">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:130px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
      <input type="text" style='width:180px' disabled="disabled">
    </div> -->
    <zjrk-Dialog :addProductData="transmitData" v-if="addshow" @addProductBack="callback"></zjrk-Dialog>

  </div>
</template>

<script>
  import zjrkDialog from "./zjrkDialog";
  import request from '@/utils/request';
  import { getToken } from "@/utils/auth";
  export default {
    name: "Role",
    components:{
    //   wizuAddDialog,
    zjrkDialog
    },
    data() {
      return {
            //记录分页数据
        localPage:undefined,
        localSize:undefined,
        loading:false,
        bukedianji:false,
        //物料编码
        wlBianma:'',
        //记录当前row
        currentRow:null,
        // 表单校验
        rules: {
          // pickName: [
          //   { required: true, message: "申请名称不能为空", trigger: "blur" }
          // ],
          wnameSJ: [
            { required: true, message: "仓库不能为空", trigger: "blur" }
          ],
          planMonth: [
            { required: true, message: "申请月份不能为空", trigger: "blur" }
          ],
        },
        reportData:[],
        defaultProps: {
          children: "childList",
          label: "wname"
        },
        // 用户导入参数
        // upload: {
        //   // 是否显示弹出层（用户导入）
        //   open: false,
        //   // 弹出层标题（用户导入）
        //   title: "",
        //   // 是否禁用上传
        //   isUploading: false,
        //   // 是否更新已经存在的用户数据
        //   updateSupport: 0,
        //   // 设置上传的请求头部
        //   headers: { Authorization: "Bearer " + getToken() },
        //   // 上传的地址
        //   url:   + '/material/apply/statistics/importWz'
        // },
        banzuArr:[],//班组数据
        zjlyArr:[],
        queryParams:{
          id:'',
          waId:'',//仓库id
          pickName:'',
          planMonth:'',
          useing:'',
          wnameSJ:'',
          wzPickingApplyInfos:[]
        },
        addshow:false,
        transmitData:{},//传给子集的数据
        shuliangSum:0,//总数量
        jinesum:0,//总金额
        tableDataxunz:'',
        dialogVisible:false,
        //是否配送
        statusOptions:[
          {value:'1',label:'是'},
          {value:'2',label:'否'}
        ],
        optionsleixing:[
          {value:'1',label:'设备采购'},
          {value:'2',label:'备件消耗材料采购'}
        ],//类型数据

        optionscgzq:[//采购周期
          {value:'1',label:'年'},
          {value:'2',label:'季'},
          {value:'3',label:'月'}
        ],
        //单位数据
        optionsdanwei:[
          {value:'1',label:'支'},
          {value:'2',label:'桶'},
          {value:'3',label:'箱'},
          {value:'4',label:'把'},
          {value:'5',label:'克'},
          {value:'6',label:'卷'},
        ],
        //总数居
        shenqingxinxi:{
          inputBiaoTi:'ceshi',//标题
          leixngXL:'1',//类型下拉
          cgzq:'1',//采购周期
          nianfen:'',//年份
          jidu:'',//季度
          beizhu:'',//备注
        },
        //采购信息
        caigouxinxi: {
          inputBiaoTi:'',//标题
          ghsj:'',//供货时间
          cgjh:'',//采购计划
          gouzhiliyou:'',//购置理由
          beizhu:'',//备注
        },
         obj: {},
        tableDatajihuaXZ:[],//选中的数据
        //去重
        planid:[],
        leixng:'post',
        arrId:[],
        headers: { Authorization: "Bearer " + getToken()},
      };
    },

    created() {
      console.log('接收-采购申请详情',this.$route.query)
      var myDate = new Date();
      var pp =myDate.getMonth()+1;       //获取当前月份(0-11,0代表1月)
      if(pp<9){
        pp = "0"+pp
      }
      var ri = myDate.getDate()
      this.queryParams.planMonth = myDate.getFullYear()+'-'+pp;
      this.queryParams.pickName = myDate.getFullYear()+'-'+pp+'-'+ri+'-'+'直接入库'
      this.getTreeselect()
      this.XQpage = this.$route.query.page
      this.XQsize = this.$route.query.size
     
    },
    methods: {
   httpRequest(params) {
      // 上传我们需要传给后台两个必传参    file 和 filename  至于文件里面的内容后台处理就好
      let formdata = new FormData();
      formdata.append("excelFile", params.file);
      formdata.append("FileName", params.file.name);
      // 这时候是打印不出来formdata的 只能通过 .get('File') 看是否append到formdata里
      // this.$api.machine
        // 调用接口的话 都是封装后的 下面会贴一下我们的接口
        this.importfacestatistics(formdata)
    },
    // 导入 
     // 接口这部分大概也没什么要说的 无非就是 请求的方式 传的参数  以及 请求头
    importfacestatistics(formdata){
        // const baseUrl = window.config.API_HOST
        // console.log(formdata)
            request({
            url: process.env.VUE_APP_BASE_API+'/material/apply/statistics/importWz',
          method: 'post',
            data: formdata,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
          if (response.code == '200') {
            this.$message.success('导入成功');
            console.log(response.data)
            response.data.forEach((item,index) =>{
          if(this.xqJhid().indexOf(item.id)==-1) {
            this.queryParams.wzPickingApplyInfos.push(response.data[index])
          }
        })
            console.log(this.queryParams.wzPickingApplyInfos)
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch(e => {
          this.$message.error(e)
        });
    },
      //查询
    //   search:function(){
    //     debugger
    //     this.loading=true
    //     var obj={}
    //     obj.wzPickingApplyId = this.$route.query.pp.row.id
    //     request({
    //       url: '/material/apply/putStorageById',
    //       method: 'get',
    //       params:obj
    //     }).then(response => {
    //       this.loading=false
    //       this.queryParams = response.data
    //       this.queryParams.wnameSJ=response.data.waName
    //       for (var i=0;i<this.queryParams.wzPickingApplyInfos.length;i++){
    //         this.queryParams.wzPickingApplyInfos[i].storageNum = this.queryParams.wzPickingApplyInfos[i].storageNum +  this.queryParams.wzPickingApplyInfos[i].demandNum
    //       }
    //     });
    //   },
         //返回
      goback () {
         this.$router.push({path:'/warehouseManagement/zjRuku',query:{page:this.XQpage,size:this.XQsize}});
      },
      getTreeselect() {
        request({
          url: '/system/warehouse/listTree',
          method: 'get',
        }).then(response => {
          this.reportData =  response.data;
        });
      },
      handleNodeClickSJ:function(node){
        console.log(node,'node')
        this.queryParams.waId = node.id
        this.queryParams.wnameSJ = node.wname
        this.$refs.selectReport.blur()
      },
      //计划价修改
      keydownBtn (row) {
        if(row.planPrice<0||row.planPrice==null) {
          row.planPrice = 0
          this.$message({
            type: 'info',
            message: '计划价不能为负数'
          });
        }
      },
     // 需求计划id
    xqJhid () {
      let planid=[]
      this.queryParams.wzPickingApplyInfos.forEach(item =>{
        planid.push(item.id)
      })
      return planid
    },
      //键盘按下事件
      xqkeydownBtn:function(row){
        // if(row.demandNum>row.storageNum){
        //   row.demandNum= row.storageNum
        //   this.$message({
        //     type: 'info',
        //     message: '入库数量不能大于未入库数量'
        //   });
        // }
        if(row.demandNum<0){
          // row.demandNum = 0
          this.$message({
            type: 'info',
            message: '入库数量不能为负数'
          });
        }
        this.currentRow = row
      },
      //弹框关闭回调函数
      callback:function(msg){
        // debugger
        this.addshow= false
        console.log(this.xqJhid())
       msg.forEach((item,index)=>{
         if(this.xqJhid().indexOf(item.id)==-1){
           msg[index].demandNum=0
           this.queryParams.wzPickingApplyInfos.push(msg[index])
         }
       })
        // this.queryParams.wzPickingApplyInfos= this.deteleObject(this.queryParams.wzPickingApplyInfos.concat(msg))
        console.log('返回数据',msg)
        // this.xqJhid()
      },
      //表格复选框监听
      handleSelectionChange:function(row){
        console.log(row)
        this.tableDatajihuaXZ = row
        // var arr=[]
        // for (var i=0;i<row.length;i++){
        //   arr.push(row[i].id/1)
        // }
        // this.arrId = arr
        // console.log('this.arrId ', this.arrId )

      },
      //修改删除
      // xgshanchu:function(){
      //   this.loading=true
      //   request({
      //     url: '/material/info/delInventoryDetails',
      //     method: 'delete',
      //     data:this.arrId
      //   }).then(response => {
      //     this.search()
      //   });
      // },
      //删除
      deleteBtn:function () {
        for (var i=0;i< this.queryParams.wzPickingApplyInfos.length;i++){
          for(var j=0;j<this.tableDatajihuaXZ.length;j++){
            if(this.queryParams.wzPickingApplyInfos[i]==this.tableDatajihuaXZ[j]){//相等
              this.queryParams.wzPickingApplyInfos.splice(i,1)
              this.fuzhiIndex()
            }
          }
        }
        // debugger
        // if(this.queryParams.wzPickingApplyInfos.length>0){
        //   this.bukedianji=true
        // }else {
        //   this.bukedianji=false
        // }
        this.fuzhiIndex()
      },
      //重新赋值index
      fuzhiIndex:function(){
        for (var i=0;i<this.queryParams.wzPickingApplyInfos.length;i++){
          this.queryParams.wzPickingApplyInfos[i].index =i
        }
      },
      //选择
      choose:function () {
        // debugger
        if(!this.queryParams.wnameSJ){
          this.$message({
            type: 'warning',
            message: '请选择仓库！'
          });
          return
        }
        this.addshow=true
        var pp={
          id:this.queryParams.waId
        }
        this.transmitData=pp

      },
        //键盘回车
      keyupBtn (scope) {
        const len = this.queryParams.wzPickingApplyInfos.length
        const val = this.currentRow
        console.log(val)
       this.queryParams.wzPickingApplyInfos.forEach((item,index) =>{
          if(item===val) {
            if(index<len-1) {
              this.$refs['mark' + (index + 1)].focus()
            }else {
              this.$refs['mark' + (0)].focus()
            }
          }
        })
      },
      //产品表格监听
      chanpinonChange(val) {
        console.log(val)
      },
      //分页
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      tijiao:function () {
        // if(this.queryParams.planMonth==''){
        //   this.$message({
        //     type: 'warning',
        //     message: '申请月份不能为空！'
        //   });
        //   return
        // }
        if(this.queryParams.wnameSJ==''){
          this.$message({
            type: 'warning',
            message: '请选择仓库！'
          });
          return
        }
        if(this.queryParams.wzPickingApplyInfos.length<1) {
          this.$message({
            type: 'warning',
            message: '增加的数量不能为零'
            });
            return
        }
        for (let i = 0; i < this.queryParams.wzPickingApplyInfos.length; i++) {
          if(this.queryParams.wzPickingApplyInfos[i].demandNum<=0||this.queryParams.wzPickingApplyInfos=='') {
             this.$message({
            type: 'warning',
            message: '请填写正确的数量'
          });
          return
          }

        }
        this.loading = true
        console.log(this.queryParams)
        request({
          url:'material/apply/directPutStorage',
          method: 'post',
          data:this.queryParams
        }).then(response => {
          this.loading = false
          this.goback()
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          // this.$router.push({path:'/warehouseManagement/'});
        });

      },


    }
  };
</script>
<style scoped  lang="scss">
  .tjsqstyle .shenqing{
    color: #05A380;
    font-weight: 700;
    margin-left: 15px;
  }
   .inputme {
  /* width: 1346px; */
  height:57px;
  overflow: hidden;
  box-sizing: border-box;
  /* overflow-x: scroll;
  overflow-y: hidden;
  position: relative; */
}
.inputme input {
  height: 57px;
  float: left;
  font-size: 14px;
  color: #606266;
  border: 1px solid #dfe6ec;
  box-sizing: border-box;
  background-color: #fff;
  /* border-bottom: 1px solid #dfe6ec; */
}
element.style{
    margin-left: 10px;
}
.el-button--mini {
    margin-left:10px
}
</style>

